package com.jd.basic.intercepto;
import com.jd.basic.anno.PreAuthorize;
import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.RsaUtils;
import com.jd.basic.jwt.UserInfo;
import com.jd.basic.utils.Payload;
import com.jd.basic.utils.ThreadLocalUtil;
import com.jd.system.mapper.PermissionMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;

/**
* @Description: 登录拦截器
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/6/13 16:54
*/
@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${jwt.rsa.pub}")
    private String jwtPubKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       System.out.println("444444444444");
        // 1.获取前端请求头中的token信息
        String token = request.getHeader("token");

        // 2.判断前端请求是否携带token，如果携带那么进入判断
        if(!StringUtils.isEmpty(token)){
//            // 2.1.根据token获取到Redis中的用户信息
//            Object logininfo = redisTemplate.opsForValue().get(token);
            // 获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtPubKey).getFile());
            // 获取身体（载荷）
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            if(null != payload && payload.getUserInfo() != null){
                UserInfo userInfo = payload.getUserInfo();
                // 将用户放到threadLocal里
                ThreadLocalUtil.setThreadLocal(userInfo);
                if (userInfo.getLogininfo().getType() == 0){
                    // 判断员工是否有sn的权限
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 从方法对象得到指定注解
                    PreAuthorize methodAnnotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    // 如果注解为空，说明这是一个公共资源,如果不为空，则是需要通过权限判断
                    if (methodAnnotation != null){
                        // 获取sn，即按钮权限
                        String permission = methodAnnotation.sn();
//                        // 获取该用户所有的按钮权限
//                        List<String> permissions = permissionMapper.findSNByLogininfoId(userInfo.getLogininfo().getId());
                        if (!userInfo.getPermissions().contains(permission)){
                            // 员工所有的权限不包含访问的权限，那么直接设置响应信息并拦截
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                        }
                    }
                }
//                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}